<template>
  <div class="page-container">
    <!-- 思维导图区域 -->
    <div class="mindmap-container">
      <slot></slot>
    </div>

    <!-- 数据流展示区域 -->
    <div class="stream-container" v-if="streamData.length > 0">
      <div class="stream-header">
        <h3>数据流</h3>
        <button @click="closeConnection" class="close-btn">关闭连接</button>
      </div>
      <div class="stream-content">
        <div v-for="(item, index) in streamData" :key="index" class="stream-item">
          <pre>{{ item }}</pre>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      arg: {
        industry_name: "中国AI 50",
        custom_urls: [],
        sites: ["google.com", "qianzhan.com", "zhihu.com"],
      },
      streamData: [], // 存储接收到的数据流
      isConnected: false // 连接状态标志
    };
  },
  mounted() {
    this.initStream();
  },
  beforeDestroy() {
    this.closeConnection();
  },
  methods: {
    closeConnection() {
      // 关闭连接的逻辑
      this.isConnected = false;
      this.streamData = [];
      console.log('已关闭数据流连接');
    },
    initStream() {
      const url = `${process.env.VUE_APP_API_SERVER}/api/industrial/process_stream`;
      const accessToken = localStorage.getItem('access_token');
      const tokenType = localStorage.getItem('token_type');

      try {
        fetch(url, {
          method: 'POST',
          headers: {
            'Authorization': `${tokenType} ${accessToken}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(this.arg)
        }).then(response => {
          const reader = response.body.getReader();
          const decoder = new TextDecoder();

          const processStream = async () => {
            while (true) {
              const { done, value } = await reader.read();
              if (done) {
                console.log('Stream complete');
                break;
              }
              const chunk = decoder.decode(value);
              // 处理接收到的数据
              try {
                const data = chunk.split('\n').filter(line => line.trim());
                data.forEach(item => {
                  if (item) {
                    this.streamData.push(JSON.parse(item));
                  }
                });
              } catch (e) {
                console.error('数据解析错误:', e);
              }
            }
          };

          processStream().catch(error => {
            console.error('Stream processing error:', error);
          });
        });

        this.isConnected = true;
      } catch (error) {
        console.error('连接错误:', error);
        this.isConnected = false;
      }
    }
  }
};
</script>

<style scoped>
.page-container {
  position: relative;
  width: 100%;
  height: 100%;
}

.mindmap-container {
  width: 100%;
  height: 100%;
}

.stream-container {
  position: fixed;
  right: 20px;
  top: 20px;
  width: 300px;
  max-height: 80vh;
  background: white;
  border: 1px solid #eee;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  z-index: 1000;
}

.stream-header {
  padding: 10px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stream-header h3 {
  margin: 0;
  font-size: 16px;
}

.close-btn {
  padding: 4px 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: white;
  cursor: pointer;
}

.close-btn:hover {
  background: #f5f5f5;
}

.stream-content {
  padding: 10px;
  max-height: calc(80vh - 50px);
  overflow-y: auto;
}

.stream-item {
  padding: 8px;
  border-bottom: 1px solid #eee;
  word-break: break-all;
}

.stream-item:last-child {
  border-bottom: none;
}

.stream-item pre {
  margin: 0;
  white-space: pre-wrap;
  font-family: monospace;
  font-size: 12px;
}
</style>